import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/material.dart';

/// 页面状态类型
enum ViewState {
  initializing, //初始化
  idle, // 咸鱼状态
  busy, //加载中
  empty, //无数据
  error, //加载失败
  noNetwork;//无网络
}


abstract class XinHeSinglePageRefreshController extends GetxController {

  /// 分页第一页页码
  static const int pageNumFirst = 1;

  final viewState = ViewState.initializing.obs;

  /// 分页条目数量
  int pageSize = 10;

  /// 当前页码
  int currentPageNum = pageNumFirst;

  bool initialRefresh = false;

  late RefreshController refreshController = RefreshController();
  final ScrollController _scrollController = ScrollController(keepScrollOffset: true);
  ScrollController get scrollController => _scrollController;

  late int allData = 0;

  @override
  void onInit() {
    setInitial();
    super.onInit();
  }

  @override
  void onClose() {
    refreshController.dispose();
    super.onClose();
  }

  @override
  void onReady() {
    // initData();
    super.onReady();
  }

  initData() async {
    await onRefresh(init: true);
  }

  setInitial() {
    viewState.value = ViewState.initializing;
  }

  setIdle() {
    viewState.value = ViewState.idle;
  }

  setError() {
    viewState.value = ViewState.error;
  }

  setEmpty() {
    viewState.value = ViewState.empty;
  }

  setBusy() {
    viewState.value = ViewState.busy;
  }

  setNoNetWork(){
    viewState.value = ViewState.noNetwork;
  }

  Future<int> loadData({int pageNum = 1});

  Future<List> onRefresh({bool init = false}) async {
    print("刷新");
    try {
      // if ( viewState.value == ViewState.error || allData == 0 ) {
      //   setInitial();
      // }
      currentPageNum = pageNumFirst;
      var dataLength = await loadData(pageNum: pageNumFirst);
      if (dataLength == 0) {
        refreshController.refreshCompleted(resetFooterState: true);
        allData = 0;
        setEmpty();
      } else {
        refreshController.refreshCompleted();
        allData = dataLength;
        setIdle();
      }
      return [];
    } catch (e) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (allData > 0) {
        refreshController.refreshFailed();
      }else {
        refreshController.refreshFailed();
        setError();
      }
      return [];
    }
  }

  // Future<List> loadMore() async {
  //   try {
  //     var data = await loadData(pageNum: ++currentPageNum);
  //     if (data.isEmpty) {
  //       currentPageNum--;
  //       refreshController.loadNoData();
  //     } else {
  //       list.addAll(data);
  //       if (data.length < pageSize) {
  //         refreshController.loadNoData();
  //       } else {
  //         refreshController.loadComplete();
  //       }
  //     }
  //     return data;
  //   } catch (e) {
  //     currentPageNum--;
  //     refreshController.loadFailed();
  //     return list;
  //   }
  // }

}
